package com.xxx.meter.ui.info.param;

import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.xxx.meter.R;
import com.xxx.meter.base.BaseActivity;
import com.xxx.meter.model.http.Api;
import com.xxx.meter.model.http.ApiCallback;
import com.xxx.meter.model.http.bean.MachineTypeBean;
import com.xxx.meter.model.http.bean.MachineChildBean;
import com.xxx.meter.model.http.bean.base.BaseBean;
import com.xxx.meter.model.http.bean.base.PageBean;
import com.xxx.meter.model.utils.ButtonUtil;
import com.xxx.meter.model.utils.ToastUtil;
import com.xxx.meter.ui.info.web.InfoFindWebActivity;
import com.xxx.meter.ui.info.adapter.IndexDeviceAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class InfoMachineFindIndexActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.main_title)
    TextView mTitle;
    @BindView(R.id.index_device_tab)
    TabLayout mTab;

    @BindView(R.id.main_recycler)
    RecyclerView mRecycler;
    @BindView(R.id.main_refresh)
    SwipeRefreshLayout mRefresh;
    @BindView(R.id.not_net)
    ImageView mNotNet;
    @BindView(R.id.not_data)
    ImageView mNotData;

    @BindView(R.id.index_btn)
    Button mBtn;

    private List<MachineTypeBean> mTypeList = new ArrayList<>();
    private List<MachineChildBean> mChildList = new ArrayList<>();
    private Map<String, List<MachineChildBean>> mChildMap = new HashMap<>();
    private IndexDeviceAdapter mAdapter;
    private int type;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_index;
    }

    @Override
    protected void initData() {
        mTitle.setText("选择设备");
        mBtn.setVisibility(View.GONE);
        type = getIntent().getIntExtra("type", 0);

        mAdapter = new IndexDeviceAdapter(mChildList);
        mRecycler.setLayoutManager(new GridLayoutManager(this, 3));
        mRecycler.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(this);
        mRefresh.setOnRefreshListener(this);

        loadDeviceTypeList();
    }

    @OnClick({R.id.main_return, R.id.index_btn, R.id.not_net, R.id.not_data})
    public void OnClick(View view) {
        if (ButtonUtil.isFastClick()) return;
        switch (view.getId()) {
            case R.id.main_return:
                finish();
                break;
            case R.id.not_net:
                loadDeviceTypeList();
                break;
            case R.id.not_data:
                loadDeviceTypeList();
                break;
            case R.id.index_btn:
                int childPosition = mAdapter.getPosition();
                if (childPosition == -1) {
                    ToastUtil.showToast("请选择需要查看设备");
                    return;
                }
                MachineChildBean bean = mChildList.get(childPosition);
                Intent intent = null;
                switch (type) {
                    case 1:
                        intent = new Intent(this, InfoFindWebActivity.class);
                        intent.putExtra("machineId", bean.getId());
                        intent.putExtra("machineType", bean.getType());
                        intent.putExtra("title", bean.getName());
                        intent.putExtra("type", 1);
                        break;
                    case 0:
                        intent = new Intent(this, InfoMachineRecordActivity.class);
                        intent.putExtra("machineId", bean.getId());
                        intent.putExtra("machineType", bean.getType());
                        intent.putExtra("machineName", bean.getName());
                        break;
                }
                if (intent != null) {
                    startActivity(intent);
                }
                break;
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (ButtonUtil.isFastClick()) return;
        mAdapter.setPosition(position);
        mBtn.setVisibility(View.VISIBLE);
    }

    @Override
    public void onRefresh() {
        mRefresh.setRefreshing(false);
    }

    /**
     * @Model 加载巡机类型列表
     */
    private void loadDeviceTypeList() {
        Api.getInstance().getDeviceTypeList()
                .flatMap(new Function<BaseBean<PageBean<MachineTypeBean>>, Observable<BaseBean<List<MachineChildBean>>>>() {
                    @Override
                    public Observable<BaseBean<List<MachineChildBean>>> apply(BaseBean<PageBean<MachineTypeBean>> objectBaseBean) {
                        mTypeList.clear();
                        mTypeList.addAll(objectBaseBean.getData().getList());

                        //切换到原有主线程
                        InfoMachineFindIndexActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //重新添加所有数据
                                for (MachineTypeBean machineBean : mTypeList) {
                                    mTab.addTab(mTab.newTab().setText(machineBean.getName()));
                                }

                                mTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                                    @Override
                                    public void onTabSelected(TabLayout.Tab tab) {
                                        List<MachineChildBean> machineChildBeans;
                                        try {
                                            machineChildBeans = mChildMap.get(mTypeList.get(tab.getPosition()).getType());
                                        } catch (Exception e) {
                                            ToastUtil.showToast("网络错误");
                                            return;
                                        }

                                        mChildList.clear();
                                        mChildList.addAll(machineChildBeans);
                                        mAdapter.setPosition(-1);
                                        mBtn.setVisibility(View.GONE);
                                    }

                                    @Override
                                    public void onTabUnselected(TabLayout.Tab tab) {

                                    }

                                    @Override
                                    public void onTabReselected(TabLayout.Tab tab) {

                                    }
                                });
                            }
                        });
                        return Api.getInstance().getAllDeviceList();
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ApiCallback<List<MachineChildBean>>(this, true) {

                    @Override
                    public void onSuccess(List<MachineChildBean> dataList) {
                        mChildList.clear();
                        mChildMap.clear();

                        if (dataList == null || dataList.size() == 0) {
                            mNotNet.setVisibility(View.GONE);
                            mNotData.setVisibility(View.VISIBLE);
                            mRefresh.setVisibility(View.GONE);
                            mRefresh.setRefreshing(false);
                            return;
                        }

                        //做一次数据处理
                        for (MachineTypeBean machineBean : mTypeList) {
                            List<MachineChildBean> list = new ArrayList<>();
                            for (MachineChildBean data : dataList) {
                                if (data.getType().equals(machineBean.getType())) {
                                    list.add(data);
                                }
                            }
                            mChildMap.put(machineBean.getType(), list);
                        }

                        List<MachineChildBean> machineChildBeans = mChildMap.get(mTypeList.get(0).getType());
                        mChildList.addAll(machineChildBeans);

                        //然后刷新适配器
                        mNotNet.setVisibility(View.GONE);
                        mNotData.setVisibility(View.GONE);
                        mRefresh.setVisibility(View.VISIBLE);
                        mAdapter.notifyDataSetChanged();
                        mRefresh.setRefreshing(false);
                    }

                    @Override
                    public void onError(int errorCode, String errorMessage) {
                        ToastUtil.showToast(errorMessage);
                        mNotNet.setVisibility(View.VISIBLE);
                        mNotData.setVisibility(View.GONE);
                        mRefresh.setVisibility(View.GONE);
                        mRefresh.setRefreshing(false);
                    }
                });
    }
}
